
from glob import glob

from nrnDoAll import nrnDoAll


import re
#srcDir = "/home/michael/debs/data/"
#srcDir = "N:/BBSRC 2009-12 Measuring Microscope/NEUROMORPH/xyz raw/"

from nrnLocations import srcFilesDir as srcDir
from nrnLocations import problemFilenameLoc,problemConversionLoc


globPattern = srcDir + "*/*.txt"


problemFiles = []

fNameRe = re.compile("""^(?P<cellType>\w+) \s+ (?P<cellNumber>[0-9]+ ( \s+ [0-9]+([.][0-9]+)?)? ) \s+ (?P<fcontents>nrn|ns) \s? (?P<analysisdate>[0-9]+ (\s* V[0-9]+)? ).txt$""", re.DOTALL| re.VERBOSE) 


nsFiles = {}
nrnFiles = {}

fDicts = {"nrn":nrnFiles, "ns":nsFiles}

for filename in sorted(glob(globPattern)):
    filename = filename.replace("\\","/")
    t = filename.split("/")
    d,f = t[-2:]
    
    dToks = d.split()
    if len(dToks) == 2:
        cellType, cellNumber = dToks
        cellVersion = ""
    elif len(dToks)==3:
        cellType,cellNumber ,cellVersion = dToks
    else:
        problemFiles.append(filename)
        continue
    
    m = fNameRe.match(f)
    if m:
        g = m.groupdict()
        c = ( g["cellType"], g["cellNumber"], g["analysisdate"] )
        print c, f
        assert not c in fDicts[ g["fcontents"] ]
        fDicts[ g["fcontents"] ][c] = f
    else:
        print f, "No match"
        problemFiles.append(f)
        continue

fPL = open(problemFilenameLoc,"w")
print "Problems:"
for p in problemFiles:
    if p.count("nrn + NS") != 0: continue 
    print p
    fPL.write("%s\n"%p)
fPL.close()
    


print "\n\n\n"
# Create a list of all the file indices:
cells = set( fDicts["ns"].keys() + fDicts["nrn"].keys() )


problemConversions = []
okConversions = []

ignores = [ ] 
#('cIN', '961104 1.4', '100331 V1'),
#            ('cIN', '961110 1.1', '100329'),
#            ('cIN', '971003 3', '100326 V1'),
#            ('cIN', '971003 3', '100326 V2'),
#            ('cIN', '961104 1.3', '100331'),
#            ('cIN', '961104 1.4', '100331 V2'),
#            ]
            
from StringIO import StringIO
import traceback
      
for c in cells:
    print c
    assert c in fDicts["ns"] 
    assert c in fDicts["nrn"]
    if c in ignores: continue
    
    #nrnDoAll( nrnType = c[0], nrnNumber=c[1], nrnVersion="",nrnDate=c[2])
    
    try:
        nrnDoAll( nrnType = c[0], nrnNumber=c[1], nrnVersion="",nrnDate=c[2])
        okConversions.append( c )
    except Exception as e:
        obj = StringIO()
        traceback.print_exc(file=obj)
        problemConversions.append( (c,obj.getvalue() ) )
        #raise e

        
fCP = open(problemConversionLoc,"w")
for pc in problemConversions:
    fCP.write("Problem Converting file: " + str(pc[0]) +"\n" )
    fCP.write("Stack Trace:\n" )
    fCP.write(pc[1] )
    fCP.write("\n\n\n")
fCP.close()
    
print problemConversions




